using System.Net.NetworkInformation;
using Microsoft.EntityFrameworkCore;
using NLog.Web;
using Quartz;
using RCS.Config;
using Seer.SeerSocket;


var builder = WebApplication.CreateBuilder(args);


// config nlog
// builder.Logging.ClearProviders();
// builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
// builder.Host.UseNLog();


builder.Services.AddDbContext<SqliteDbContext>(opt =>
{
    string connStr = builder.Configuration.GetConnectionString("Default")!;
    opt.UseSqlite(connStr);
});


// agv socket
builder.Services.AddSingleton<Dictionary<string,SeerSocket>>(sp =>
{
    var configurationSection = builder.Configuration.GetSection("AGV");
    var options = new AgvOptions();
    configurationSection.Bind(options);

    var seerScokets = new Dictionary<string,SeerSocket>();

    foreach(var option in options){
        if(string.IsNullOrEmpty(option.Ip)) throw new ConfigurationException("AGV 的 IP 地址为空");
        if (!option.Enable) continue;

        var ping = new Ping();
        var reply = ping.Send(option.Ip);
        if(reply.Status == IPStatus.Success){
            seerScokets.Add(option.Ip,new SeerSocket(option));
        }else{
            Console.WriteLine($"{option.Ip}:跳过连接");
        }

    }
    return seerScokets; 
});



builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


// 需要开启cros
string[] urls = new[] { "*" };
builder.Services.AddCors(options =>
    options.AddDefaultPolicy(builder => builder.WithOrigins(urls)
        .AllowAnyMethod().AllowAnyHeader().AllowCredentials())
);

// Add the required Quartz.NET services
builder.Services.AddQuartz(q =>
{
    q.AddJobAndTrigger<DetectAgvJob>(builder.Configuration);
});

// Add the Quartz.NET hosted service
builder.Services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);

var app = builder.Build();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.MapGet("/", () =>
{
    return Results.Redirect("/swagger");
});

app.Run();






